package com.reviewcode.cachemicroservice.service;

import com.reviewcode.cachemicroservice.common.GenericResponse;
import com.reviewcode.cachemicroservice.common.bean.MicroCache;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author vcorazon
 * @type Class
 * @description TODO
 * @since 2021/07/22 22:16
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class CacheService {
    private final MicroCache<String, String> microCache;

    @Value("${max_capacity}")
    int maxCapacity;

    public GenericResponse getCache(String key) {
        return GenericResponse.success(microCache.get(key));
    }

    public GenericResponse storeCache(String key, String value, long duration) {
        if (microCache.size() >= maxCapacity) {
            return GenericResponse.fail("容量不足");
        }
        return GenericResponse.success(microCache.put(key, value, duration));
    }
}
